<template>
  <el-form ref="DictForm" :model="formData" :rules="formRules" label-width="90px">
    <el-form-item v-if="action === 'edit'" prop="id">
      <input type="hidden" :model="formData.id">
    </el-form-item>
    <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
    <el-row>
      <el-col :span="6" :offset="1">
        <el-form-item label="字典编码" prop="code">
          <el-input
            v-model="formData.code"
            type="text"
            placeholder="请输入字典编码"
            :readonly="action === 'edit'"
          />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="formData.name" type="name" placeholder="请输入字典名称" />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="字典排序" prop="sort">
          <el-input v-model="formData.sort" type="sort" placeholder="请输入字典排序" />
        </el-form-item>
      </el-col>
    </el-row>
    <input type="hidden" :model="formData.sysDictValues">
    <ul v-for="(item, index) in formData.sonFormData" :key="index">
      <el-row>
        <el-col :span="6">
          <input v-model="item.id" hidden>
          <el-form-item label="键" :prop="'sonFormData.' + index + '.code'" :rules="{required: true, message: '键不能为空', trigger: 'blur'}">
            <el-input v-model="item.code" type="code" placeholder="" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="值" :prop="'sonFormData.' + index + '.name'" :rules="{required: true, message: '值不能为空', trigger: 'blur'}">
            <el-input v-model="item.name" type="name" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="排序" prop="num">
            <el-input v-model="item.num" />
          </el-form-item>
        </el-col>
        <el-col :span="2" :offset="1">
          <el-button @click="del(index)">删除</el-button>
        </el-col>
      </el-row>
    </ul>
  </el-form>
</template>
<script>
import { get, save, update, verifyDictCode } from '@/api/admin/dict';

export default {
  name: 'DictFormDialog',
  props: {
    action: {
      type: String,
      default: 'add'
    }
  },
  data() {
    // 校验dictCode
    const checkDictCode = (rule, value, callback) => {
      if (value === '') {
        callback('字典编码不能为空！');
      } else {
        if (this.action === 'edit') {
          callback();
        }
        verifyDictCode({ code: value }).then(response => {
          if (!response.data.data) {
            callback(new Error('字典编码已存在!请替换'));
          } else {
            callback();
          }
        });
      }
    };
    return {
      formRules: {
        code: [
          { validator: checkDictCode, trigger: 'blur' }
        ],
        name: [
          { required: true, message: '字典名称不能为空！', trigger: 'blur' }
        ]
        // key: [{ required: true, message: '键不能为空', trigger: 'blur' }],
        // value: [{ required: true, message: '值不能为空', trigger: 'blur' }]
      },
      formData: {
        id: null,
        code: null,
        name: null,
        sonFormData: []
      }
    };
  },
  methods: {
    getInfo(code) {
      get({ code: code }).then(response => {
        const result = response.data;
        if (result.code === 0) {
          this.formData.id = result.data.adminDict.id;
          this.formData.code = result.data.adminDict.code;
          this.formData.name = result.data.adminDict.name;
          this.formData.sort = result.data.adminDict.sort;
          this.formData.sonFormData = result.data.sonFormData;
        } else {
          this.$notify.error({
            title: result.code,
            message: result.msg
          });
        }
      });
    },
    handleSubmit() {
      this.$refs.DictForm.validate(valid => {
        if (valid) {
          if (this.action === 'add') {
            var sysDictValues = '';
            this.formData.sonFormData.forEach(function(item) {
              sysDictValues =
                sysDictValues +
                item.id +
                ':' +
                item.code +
                ':' +
                item.name +
                ':' +
                item.num +
                ';';
            });
            this.formData.sysDictValues = sysDictValues;
            const params = { ...this.formData };
            save(params).then(response => {
              this.handleResult(response.data);
            });
          } else if (this.action === 'edit') {
            // 处理数据
            this.formData.sonFormData.forEach(function(item) {
              sysDictValues =
                sysDictValues +
                item.id +
                ':' +
                item.code +
                ':' +
                item.name +
                ':' +
                item.num +
                ';';
            });
            this.formData.sysDictValues = sysDictValues;
            update(this.formData).then(response => {
              this.handleResult(response.data);
            });
          }
        }
      });
    },
    handleResult(obj) {
      if (obj.code === 0) {
        this.$notify({
          title: '提示',
          message: obj.msg,
          type: 'success'
        });

        this.$parent.$parent.customFormInitOption.showModal = false;
        this.$parent.$parent.$refs.customTable.query();
        this.reset();
      } else {
        this.$notify.error({
          title: obj.code,
          message: obj.msg
        });
      }
    },
    reset() {
      this.formData.sonFormData = [];
      this.count = 0;
      this.$refs.DictForm.resetFields();
    },
    add() {
      if (this.count === undefined) {
        this.count = 0;
      }
      this.count = this.count + 1;
      this.formData.sonFormData.push({
        id: 'sonDict' + this.count,
        key: '',
        value: '',
        sort: ''
      });
      console.log(this.formData.sonFormData);
    },
    del(index) {
      this.formData.sonFormData.splice(index, 1);
    }
  }
};
</script>
